import React, { FC, useMemo } from "react";
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";
import { QuestionRadioStatComponentType } from "./interface";
import { PIE_COLORS } from "../../../constant";

function format(n: number) {
  return (n * 100).toFixed(2);
}

const StatComponent: FC<QuestionRadioStatComponentType> = ({ stat = [] }) => {
  const sum = useMemo(() => {
    // 缓存起来
    let s = 0;
    stat.forEach((i) => (s += i.count));
    return s;
  }, [stat]);
  return (
    <div style={{ width: "300px", height: "400px" }}>
      <ResponsiveContainer width="100%" height="100%">
        <PieChart width={400} height={400}>
          <Pie
            dataKey="count"
            data={stat}
            cx="50%" //x轴的偏移量
            cy="50%" //Y轴的偏移量
            outerRadius={50} //直径
            fill="#8884d8"
            label={(i) => `${i.name}_${format(i.count / sum)}%`}
          >
            {stat.map((i, index) => {
              return <Cell key={index} fill={PIE_COLORS[index]} />;
            })}
          </Pie>
          <Tooltip />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
};

export default StatComponent;
